package com.itheima.controller;

import com.itheima.pojo.*;
import com.itheima.service.ClassService;
import com.itheima.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentService studentService;

    /**
     * 新增学生
     * @param req
     * @return
     */
    @PostMapping
    public Result addStudent(@RequestBody StudentAddReq req) {
        log.info(req.toString());
        Student student = new Student(0, req.getName(), req.getNumber(), req.getGender(), req.getPhone(),
                req.getEducationId(), req.getStudentClass().getId(), LocalDateTime.now(),0,0);

        Boolean hasAdded = studentService.addStudent(student);
        if (hasAdded) {
            return Result.success();
        }else {
            return Result.error("添加失败");
        }
    }


    /**
     * 根据id删除
     * @param ids
     * @return
     * @throws Exception
     */
    @DeleteMapping("{ids}")
    public Result deleteStudent(@PathVariable("ids") String[] ids) throws Exception {
        Boolean hasDeleted = studentService.deleteByIds(ids);
        if (hasDeleted) {
            return Result.success();
        }else {
            return Result.error("删除失败");
        }
    }


    /**
     * 分页查询
     */
    @GetMapping
    public Result getAllStudent(@RequestParam(defaultValue = "1") Integer page,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              String name, String educationId, String number, String classId)
    {
        PageBean pb = studentService.getAllStudents(page, pageSize, name, educationId, number, classId);
        return Result.success(pb);
    }


    /**
     * 扣分和修改
     * debug:逻辑修改最好放在service
     */
    @PutMapping
    public Result updateStudent(@RequestBody StudentAddReq req) throws Exception {
        Boolean hasUpdated = studentService.updateStudent(req);
        if (hasUpdated) {
            return Result.success();
        }else {
            return Result.error("修改失败");
        }
    }
}
